package com.kfm.jdbc.day01;

import java.sql.*;

public class Demo08 {

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/scott";
        String user = "root";
        String pass = "root";

        /*
               1. 注册驱动
               2. 创建连接
               3. 创建 PreparedStatement 对象
               4. 设置参数
               5. 执行操作
               6. 解析结果
               7. 释放资源
         */

        String sql = "select empno '编号', ename '名称', job '职位', mgr, hiredate, sal, comm, deptno from emp e";
        try(
            // 创建连接
            Connection conn = DriverManager.getConnection(url, user, pass);
            // 创建 PreparedStatement 对象
            PreparedStatement preparedStatement = conn.prepareStatement(sql)
        ) {
            // 设置参数

            // 执行操作
            ResultSet resultSet = preparedStatement.executeQuery();

            // 元数据
            ResultSetMetaData metaData = resultSet.getMetaData();

            // 获取结果集列数量
            int columnCount = metaData.getColumnCount();

//            for (int i = 1; i <= columnCount; i++) {
//                String schemaName = metaData.getSchemaName(i);
//                String tableName = metaData.getTableName(i);
//
//                // 结果集中的列名
//                String label = metaData.getColumnLabel(i);
//                // 数据库中表的列名
//                String name = metaData.getColumnName(i);
//                int columnType = metaData.getColumnType(i);
//                String columnClassName = metaData.getColumnClassName(i);
//
//                System.out.println("schemaName: " + schemaName + ", tableName: " + tableName + ", label: " + label + ", name: " + name + ", columnType: " + columnType + ", columnClassName: " + columnClassName);
//            }

            while (resultSet.next()){
                for (int i = 1; i < columnCount; i++) {
                    String label = metaData.getColumnLabel(i);
                    Object object = resultSet.getObject(i);
                    System.out.print(label + ": " + object + ", ");
                }
                System.out.println();
            }


            resultSet.close();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
